package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.Blog;
import model.BlogDao;
import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class BlogLoginServlet extends HttpServlet {
    private ObjectMapper objectMapper=new ObjectMapper();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //防止传输过来的中文乱码
        req.setCharacterEncoding("utf8");
        resp.setContentType("text/html;charset=utf8");
        //获取到form表单提交过来的数据
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        //对用户名进行判定
        if(username==null||"".equals(username)||password==null||"".equals(password)){
            String html="<h1 style=\"text-align: center;\">登录失败！缺少usename或者password</h3>";
            resp.getWriter().write(html);
            return;
        }
        //对用户名和密码与数据库中的数据比对
        UserDao userDao=new UserDao();
        User user=userDao.selectByUsername(username);
        if(user==null){
            //用户不存在
            String html="<h1 style=\"text-align: center;\">登录失败！用户名或密码错误</h3>";
            resp.getWriter().write(html);
            return;
        }
        if(!password.equals(user.getPassword())){
            //密码不正确
            String html="<h1 style=\"text-align: center;\">登录失败！用户名或密码错误</h3>";
            resp.getWriter().write(html);
            return;
        }
        //用户名密码验证成功，创建会话，保存用户信息
        HttpSession session=req.getSession(true);
        //设置用户信息的键值对
        session.setAttribute("user",user);
        //重定向到博客列表页
        resp.sendRedirect("blog_list.html");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf8");
        //使用这个方法来获取用户的登陆状态
        //如果用户未登陆，这里就拿不到状态
        HttpSession session=req.getSession(false);
        if(session==null){
            User user=new User();
            String respjson=objectMapper.writeValueAsString(user);
            resp.getWriter().write(respjson);
            return;
        }
        //根据username键或得对应的用户信息的对象值
        User user= (User) session.getAttribute("user");
        if(user==null){
            user=new User();
            String respjson=objectMapper.writeValueAsString(user);
            resp.getWriter().write(respjson);
            return;
        }
        //用户确认成功，把这个对象转成字符串返回给页面
        String respjson=objectMapper.writeValueAsString(user);
        resp.getWriter().write(respjson);
    }
}
